import { useEffect, useRef, useState } from 'react'
/**
 * 一秒钟执行一次
 */
const useCountDown = ({ mis = 30 }: { mis: number }) => {
	const [counting, setCounting] = useState(false)
	const [restSecond, setRestSecond] = useState<number>(0)
	const timerRef = useRef<NodeJS.Timeout[]>([])
	const countDown = (timeLeft: number) => {
		if (timeLeft <= 0) {
			setRestSecond(0)
			setCounting(false)
			return
		}
		if (counting) {
			setRestSecond(timeLeft)
			const timerId = setTimeout(() => countDown(timeLeft - 1), 1000)
			timerRef.current.push(timerId)
		}
	}
	const clearTimer = () => {
		if (timerRef.current.length) {
			for (let time = 0; time <= timerRef.current.length; time++) {
				clearTimeout(timerRef.current.pop())
			}
		}
	}
	useEffect(() => {
		if (counting) {
			countDown(mis)
		}

		return clearTimer

		// eslint-disable-next-line react-hooks/exhaustive-deps
	}, [counting])

	return {
		counting,
		restSecond,
		start: () => {
			setCounting(true)
		},
		cancel: () => {
			clearTimer()

			setRestSecond(mis)
			setCounting(false)
		}
	}
}

export default useCountDown
